package com.yonyou.crm.cum.cumprmt.appctrl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.rest.apputil.AppRequestUtil;
import com.yonyou.crm.common.rest.constant.AppCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.cum.cumprmt.entity.CumprmtVO;
import com.yonyou.crm.cum.cumprmt.rmitf.ICumprmtRmService;

@RestController
@RequestMapping(value = "/{version}/mcum/cumprmts")
public class AppCumprmtCtrl {

	@Autowired
	private ICumprmtRmService service;
	
	/*
	 * 提交升级申请
	 */
	@RequestMapping(value = "submit", method = RequestMethod.POST)
	public Object submit(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Long cumId = paramObject.getLong("cumid");
		
		service.submit(cumId);
		return ResponseUtil.getObject("升级成功");
	}
	

	
	/**
	 * 新增与编辑
	 * @param version
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="/{objid}", method = RequestMethod.POST)
	public Object save(@PathVariable("version") String version, @PathVariable("objid") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject dataJsonObject = AppRequestUtil.getFormParamObject(request);
		JSONObject headerJson = dataJsonObject.getJSONObject("header");
		CumprmtVO vo = AppRequestUtil.getVO(headerJson, CumprmtVO.class);
		
		String errorMsg = insertValidator(vo);
		if (!errorMsg.equals("")) {
			throw new CrmMessageException(AppCodeConstant.ServerError, errorMsg);
		}
		
		if (id.equals(0L)) {
			vo = service.save(vo);
		} else {
			vo.setId(id);
			vo = service.update(vo);
		}
		
		if (vo.getId() == null) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "获取自增主键失败，未保存成功");
		}
		return ResponseUtil.getObject();
	}
	
	/**
	 * 数据校验
	 * @param cumprmt
	 * @return
	 */
	private String insertValidator(CumprmtVO vo) {
		String Message = "";
		if (vo == null) {
			Message = "客户升级单实体转换失败";
		}
		return Message;
	}
	
}
